package com.wang.concurrency;

import java.util.concurrent.*;

/**
 * Executors.newCachedThreadPool()
 * @author simonwang
 *
 */
public class ThreadPool {

	
	public static void main(String[] args) {
		
		ExecutorService pool = getThreadPool();

		pool.submit(new ConcreteRunnable());		
		pool.submit(new ConcreteRunnable());
		//用完一个线程池后, 应该调用该线程池的shutdown()方法,该方法将启动线程池关闭序列,不再接收新任务,
		//但会将以前所有已提交的任务尽快执行完成.所有任务都执行完,池中所有线程都会死亡.
		pool.shutdown();		
	}
	
	
	private static ExecutorService getThreadPool(){
		
		return Executors.newCachedThreadPool(new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {				
				return new Thread(r);
			}
		});
		
		 // return Executors.newCachedThreadPool();
        // return Executors.newFixedThreadPool(2);
        // return Executors.newSingleThreadExecutor();		
	}
	
	private static class ConcreteRunnable implements Runnable{
		
		@Override
		public void run() {
			for(int i=0;i<10;i++){
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
				 System.out.println(Thread.currentThread().getName() + " : " + i);
			}
		}
		
	}
}
